#include "http_get.h"
#include "wx_api.h"

#include <QFile>
#include <QNetworkCookie>
#include <QNetworkCookieJar>

Http_Get::Http_Get(QObject *parent) : QObject(parent)
{

}

Http_Get::~Http_Get()
{

}

void Http_Get::get(QString url, bool needCookie)
{
    QNetworkRequest request(url);

    m_url = url;

    // load cookie
    if(needCookie) {
        QFile file(QWXDIR + "/" + COOKIE_FILENAME);
        if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream out(&file);
            QList<QNetworkCookie> cookies = QNetworkCookie::parseCookies(out.readAll().toUtf8());
            QVariant var;
            var.setValue(cookies);
            request.setHeader(QNetworkRequest::CookieHeader, var);
        }
    }

    m_sslErrorConnection = connect(&m_nam, &QNetworkAccessManager::sslErrors,
                                [this](QNetworkReply* reply, const QList<QSslError> & errors) {
                                    reply->ignoreSslErrors(errors);
                                });

    m_finishConnection = connect(&m_nam, &QNetworkAccessManager::finished,
                                [this](QNetworkReply* reply) {
                                    m_cookies = m_nam.cookieJar()->cookiesForUrl(QUrl(m_url));
                                    // overloaded by inhertied class object
                                    this->finished(reply);

                                    disconnect(m_sslErrorConnection);
                                    disconnect(m_finishConnection);
                                });
    m_nam.get(request);
}
